In JavaScript, functions can be defined using Function Declarations or Function Expressions. While they serve similar purposes, they differ in terms of syntax, behavior, and hoisting.
function
keyword followed by the function name.Example:
function greet() {
console.log("Hello from Function Declaration!");
}
greet(); // Output: Hello from Function Declaration!
Output: Hello from Function Declaration!
Example:
const greet = function() {
console.log("Hello from Function Expression!");
};
greet(); // Output: Hello from Function Expression!
Output: Hello from Function Expression!
Aspect | Function Declaration | Function Expression |
---|---|---|
Syntax | function name() { ... } |
const name = function() { ... } |
Hoisting | Can be called before its definition. | Cannot be called before its definition. |
Use Case | Used for named reusable functions. | Used for anonymous functions or assigning functions to variables. |